import * as signalR from '@microsoft/signalr';
import { ElNotification } from 'element-plus';
import { pushMessage } from './messageBus.js';
import { ElMessageBox } from 'element-plus';
import store from '@/store/index';

export default function(http, receive) {
  let connection;
  http.post('api/user/GetCurrentUserInfo').then((result) => {
    connection = new signalR.HubConnectionBuilder()
      .withAutomaticReconnect()
      // 使用同源相对路径，交由vite代理转发，避免CORS
      .withUrl(`/message?userName=${encodeURIComponent(result.data.userName)}`,{
        //withCredentials: true // 启用凭证模式
       // accessTokenFactory: () => store.getters.getToken()
    })
      //.withUrl(`${http.ipAddress}message`)
      .build();

    connection.start().catch((err) => console.log(err.message));
    //自动重连成功后的处理
    connection.onreconnected((connectionId) => {
      console.log(connectionId);
    });
    connection.on('ReceiveHomePageMessage', function(data) {
      //console.log(data);
      switch (data.value) {
        case 'logout':
          showLogoutMessage(data);
          return;
        default:
          const date = data.date || new Date().toLocaleString();
          const title = data.title || '系统消息';
          const message = (data.message||'') + '';
          ElNotification.success({ title, message, type: 'success' });
          // 推入消息面板
          // 拼装可跳转的路由（跳到订单列表并按编号过滤/或传递编号）
          const route = data.ordernoas
            ? { path: '/so_order', query: { ordernoas: data.ordernoas } }
            : null;
          pushMessage({ title, desc: message, date, tag: 'success', type: data.type || '订单', route });
          receive && receive(data);
          break;
      }
    });
  });
}
//强制用户下线
function showLogoutMessage(data) {
  store.commit('clearUserInfo', '');
  const timerId = setTimeout(() => {
    clearTimeout(timerId);
    window.location.href = '/';
  }, 5000);
  ElMessageBox.confirm(data.msg, '警告', {
    center: true,
    showCancelButton: false,
    closeOnClickModal: false,
    closeOnPressEscape: false,
    showClose: false
  }).then(() => {
    clearTimeout(timerId);
    window.location.href = '/';
  });
}
